import 'dart:async';
import 'package:flutter/foundation.dart';
import 'generated/native_video_cache_api.g.dart';

/// 统一的缓存状态
class CacheState {
  final String url;
  final CacheStatus status;
  final double progress;
  final DateTime lastUpdate;
  final int retryCount;
  final String? errorMessage;
  final int cachedSize;
  final int totalSize;

  const CacheState({
    required this.url,
    required this.status,
    required this.progress,
    required this.lastUpdate,
    this.retryCount = 0,
    this.errorMessage,
    this.cachedSize = 0,
    this.totalSize = 0,
  });

  CacheState copyWith({
    CacheStatus? status,
    double? progress,
    DateTime? lastUpdate,
    int? retryCount,
    String? errorMessage,
    int? cachedSize,
    int? totalSize,
  }) {
    return CacheState(
      url: url,
      status: status ?? this.status,
      progress: progress ?? this.progress,
      lastUpdate: lastUpdate ?? this.lastUpdate,
      retryCount: retryCount ?? this.retryCount,
      errorMessage: errorMessage ?? this.errorMessage,
      cachedSize: cachedSize ?? this.cachedSize,
      totalSize: totalSize ?? this.totalSize,
    );
  }

  @override
  String toString() => 'CacheState(url: $url, status: $status, progress: $progress, retryCount: $retryCount)';
}

/// 缓存状态监听器
typedef CacheStateListener = void Function(CacheState state);

/// 统一的缓存状态管理器
class CacheStateManager {
  static CacheStateManager? _instance;
  static CacheStateManager get instance => _instance ??= CacheStateManager._();

  CacheStateManager._();

  final Map<String, CacheState> _states = {};
  final Map<String, Set<CacheStateListener>> _listeners = {};
  final StreamController<CacheState> _stateController = StreamController<CacheState>.broadcast();

  bool _isInitialized = false;

  /// 初始化状态管理器
  void initialize() {
    if (_isInitialized) return;
    _isInitialized = true;
    debugPrint('CacheStateManager: 初始化完成');
  }

  /// 获取状态流
  Stream<CacheState> get stateStream => _stateController.stream;

  /// 更新缓存状态
  void updateState(String url, {
    CacheStatus? status,
    double? progress,
    int? retryCount,
    String? errorMessage,
    int? cachedSize,
    int? totalSize,
  }) {
    final currentState = _states[url];
    final newState = currentState?.copyWith(
      status: status,
      progress: progress,
      lastUpdate: DateTime.now(),
      retryCount: retryCount,
      errorMessage: errorMessage,
      cachedSize: cachedSize,
      totalSize: totalSize,
    ) ?? CacheState(
      url: url,
      status: status ?? CacheStatus.none,
      progress: progress ?? 0.0,
      lastUpdate: DateTime.now(),
      retryCount: retryCount ?? 0,
      errorMessage: errorMessage,
      cachedSize: cachedSize ?? 0,
      totalSize: totalSize ?? 0,
    );

    _states[url] = newState;
    _notifyListeners(url, newState);
    _stateController.add(newState);
  }

  /// 获取缓存状态
  CacheState? getState(String url) {
    return _states[url];
  }

  /// 获取所有状态
  Map<String, CacheState> getAllStates() {
    return Map.unmodifiable(_states);
  }

  /// 添加状态监听器
  void addListener(String url, CacheStateListener listener) {
    _listeners.putIfAbsent(url, () => <CacheStateListener>{});
    _listeners[url]!.add(listener);
    
    // 如果已有状态，立即通知
    final state = _states[url];
    if (state != null) {
      listener(state);
    }
  }

  /// 移除状态监听器
  void removeListener(String url, CacheStateListener listener) {
    final listeners = _listeners[url];
    if (listeners != null) {
      listeners.remove(listener);
      if (listeners.isEmpty) {
        _listeners.remove(url);
      }
    }
  }

  /// 清理指定URL的状态
  void clearState(String url) {
    _states.remove(url);
    _listeners.remove(url);
    debugPrint('CacheStateManager: 清理状态 - $url');
  }

  /// 清理所有状态
  void clearAllStates() {
    _states.clear();
    _listeners.clear();
    debugPrint('CacheStateManager: 清理所有状态');
  }

  /// 通知监听器
  void _notifyListeners(String url, CacheState state) {
    final listeners = _listeners[url];
    if (listeners != null) {
      for (final listener in listeners) {
        try {
          listener(state);
        } catch (e) {
          debugPrint('CacheStateManager: 监听器异常 - $e');
        }
      }
    }
  }

  /// 获取统计信息
  Map<String, dynamic> getStatistics() {
    final states = _states.values.toList();
    final totalUrls = states.length;
    final cachedUrls = states.where((s) => s.status == CacheStatus.cached).length;
    final cachingUrls = states.where((s) => s.status == CacheStatus.caching).length;
    final errorUrls = states.where((s) => s.status == CacheStatus.error).length;
    final totalRetries = states.fold<int>(0, (sum, s) => sum + s.retryCount);

    return {
      'totalUrls': totalUrls,
      'cachedUrls': cachedUrls,
      'cachingUrls': cachingUrls,
      'errorUrls': errorUrls,
      'totalRetries': totalRetries,
      'successRate': totalUrls > 0 ? cachedUrls / totalUrls : 0.0,
    };
  }

  /// 释放资源
  void dispose() {
    if (!_isInitialized) return;
    
    _states.clear();
    _listeners.clear();
    _stateController.close();
    _isInitialized = false;
    debugPrint('CacheStateManager: 资源释放完成');
  }
}
